package testtiles.state;

import static butines.core.math2d.Vector2DUtils.distanceSq;
import testtiles.object.Unit;
import butines.core.math2d.Vector2D;

public class UnitFollowLeaderState extends AbstractState<Unit> {
	
	private static final UnitFollowLeaderState instance = new UnitFollowLeaderState();
	
	public static UnitFollowLeaderState getInstance() {
		return instance;
	}
	
	public boolean atTargetPoint(Unit unit, Vector2D targetPoint, float minDistance) {
		return distanceSq(unit.getPosition(), targetPoint) < minDistance * minDistance;
	}
	
	@Override
	public void enter(Unit unit) {
		unit.getAnimations().getWalk().play();
		
		unit.getSteering().getOffsetPursuit().setLeader(unit.getLeader());
		unit.getSteering().getOffsetPursuit().setOffset(unit.getLeaderOffset());
		unit.getSteering().getOffsetPursuit().on();
		
		unit.getSteering().getSeparation().on();
		unit.getSteering().getCohesion().on();
	}

	@Override
	public void leave(Unit unit) {
		unit.getSteering().getOffsetPursuit().off();
		unit.getSteering().getSeparation().off();
		unit.getSteering().getCohesion().off();
	}
	
	@Override
	public void execute(Unit owner) {
		
		float dist = owner.distance(owner.getLeader());
		float offset = owner.getLeaderOffset().length();
		
		System.out.println(dist + " " + offset);
		
		if (owner.getLeader().getSpeed() < 0.05 && dist <= offset) {
			owner.doStay();
			return;
		}
		
	}
	
}
